package com.sun.future;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class AllOfExample {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始");

        // 创建多个异步任务
        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "任务1结果";
        });

        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "任务2结果";
        });

        CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "任务3结果";
        });

        // allOf: 等待所有任务完成
        CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2, task3);

        // 等待所有任务完成
        allTasks.get();
        System.out.println("所有任务已完成");

        // 获取各个任务的结果
        System.out.println("任务1结果: " + task1.get());
        System.out.println("任务2结果: " + task2.get());
        System.out.println("任务3结果: " + task3.get());

        // 更优雅的方式：使用Stream处理所有结果
        List<CompletableFuture<String>> futures = Arrays.asList(task1, task2, task3);
        CompletableFuture<List<String>> allResults = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .thenApply(v -> futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList()));

        System.out.println("所有结果: " + allResults.get());
        System.out.println("主线程结束");
    }
}
